package com.buttonpay.home;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.buttonpay.AppData;
import com.buttonpay.MD5Generator;
import com.buttonpay.Products;
import com.buttonpay.R;

public class TopUpDialog extends Dialog implements android.view.View.OnClickListener 
{

	TextView tvConfirmationText,tvDialogHeader;
	Button btnOk,btnCancel,btnOkConfirmation,btnCancelConfirmation;
	EditText etRefMobileNo,etFromNo,etAmount,etSecurePin;
	Context context;
	//String refmobileNo="",fromMobileNo="",amount="",securePin="";
	String amount="";
	Button btnOkSummary,btnContinue;
	//String operatorName;
	Products currentProdut;
	Spinner spAmount;
	TextView tvOperatorname,tvSummary;;
	private Handler myhandler=new Handler();
	private ProgressDialog pd=null;
	Handler handler=new Handler();
	MD5Generator md5Generator=new MD5Generator();
	public TopUpDialog(Context context, Products p)
	{
		super(context);
		this.context=context;
		this.currentProdut= p;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(com.buttonpay.R.layout.topup_dialog);
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

		btnOk=(Button)findViewById(R.id.btn_ok);
		spAmount=(Spinner)findViewById(R.id.spAmount);
		btnCancel=(Button)findViewById(R.id.btn_Cancel);
	 	etRefMobileNo=(EditText)findViewById(R.id.etRefMobileNo);
	 	etFromNo=(EditText)findViewById(R.id.etFromMobileNo);
	 	
	 	etAmount=(EditText)findViewById(R.id.etAmount);
	 	etSecurePin=(EditText)findViewById(R.id.etSecurePin);
		spAmount=(Spinner)findViewById(R.id.spAmount);
		tvOperatorname=(TextView)findViewById(R.id.tvOperatorName); 
		tvDialogHeader=(TextView)findViewById(R.id.dialog_header);
		tvOperatorname.setText(currentProdut.getProductName());
		
		
		//check wheather product is under airtime TopUp or UtilityPay and change the dialog header 
		if(!p.getSystemServiceID().equalsIgnoreCase("2"))
		{
			tvDialogHeader.setText("Utility Pay");
		}
			
		
	 	
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		if(currentProdut.getProductType().equalsIgnoreCase("1"))
		{
			System.out.println("Operator Name:"+currentProdut.getProductName());
			etAmount.setVisibility(EditText.GONE);
			ArrayAdapter<String> spAdapter= new ArrayAdapter<String>(context, R.layout.simple_spinner_item,new String[]{""+Integer.parseInt(currentProdut.getMaxValue())/100});
			spAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
			spAmount.setAdapter(spAdapter);
			 
		}
		else
		{
			
			spAmount.setVisibility(Spinner.GONE);
		}
		 
	 }
	 private String validateInput(String refMoNo,String fromMoNo,String pin) 
	 {
	       try
	       {
			   if(refMoNo.trim().length()==0)
		       {
				    return "Enter Reference Number";
		       }
			   if(!currentProdut.getSystemServiceID().equals("2"))
			   {
				    if(fromMoNo.trim().length()==0)
				    {
				    	return "Enter Notify Number";
				    }
			   }
			   if(fromMoNo.equals(refMoNo))
			   {
				   return "Reference Number and Notify Number Should not be same";
			   }
			    if(currentProdut.getProductType().equals("0"))
		        {
		            if(amount.trim().length()==0)
		            {
		                    return "Enter Amount";
		            }
		            else if(Integer.parseInt(amount) * 100 > Integer.parseInt(currentProdut.getMaxValue())||
		            		Integer.parseInt(amount) *100<Integer.parseInt(currentProdut.getminValue()))
		            {
		            	etAmount.setText("");
		                return "Enter Amount between "+Integer.parseInt(currentProdut.getminValue())/100
		                        +"-"+Integer.parseInt(currentProdut.getMaxValue())/100;
		            }
	
		        }
			    
//			    MD5Generator md5generator=new MD5Generator();
//			    String key=md5generator.MD5(pin);
			    System.out.println("my key:"+pin);
			    System.out.println("user pin"+AppData.getUserInfo().getIVRPassword()); 
			    
			    if(!AppData.getUserInfo().getIVRPassword().equalsIgnoreCase(md5Generator.MD5(pin)))
		        {
			    	System.out.println("My Pin:"+pin);
			    	System.out.println("User Pin:"+AppData.getUserInfo().getIVRPassword());
		        	System.out.println("pin is not same");
		        	etSecurePin.setText("");
		            return "Enter Valid PIN";
		        }
			    else
			    {
			    	System.out.println("key is same");
			    	return "success";
			    }
		        
		      //  
		        
		        
	       }
	       catch(Exception e)
	       {
	    	   e.printStackTrace();
	    	   return null;
	       }
	 
	       
	        
	 }
	public void onClick(View v) 
	{
		/** When OK Button is clicked, dismiss the dialog */
		if (v == btnOk)
		{
 
			if(currentProdut.getProductType().equals("0"))
				amount=etAmount.getText().toString();
			else
				amount=spAmount.getSelectedItem().toString();
			 
			String msg=validateInput(etRefMobileNo.getText().toString(),etFromNo.getText().toString(),etSecurePin.getText().toString());
			 
			 if(!msg.equals("success"))
             {
                 Toast.makeText(context, msg,Toast.LENGTH_LONG).show(); 
             }
			 else
			 {
				 dismiss();
				 setContentView(R.layout.confirmation_layout);
				 
				 	tvConfirmationText=(TextView)findViewById(R.id.tvConfirmationText);
				 	
					btnOkConfirmation=(Button)findViewById(R.id.btn_Ok_confirmation);
					btnCancelConfirmation=(Button)findViewById(R.id.btn_Continue_confirmation);
					if(currentProdut.getProductID().equals("5"))
					{
						tvConfirmationText.setText("Tuma LUKU ya Tsh "+amount +" Kwenda meter namba "+etRefMobileNo.getText().toString()+".");	
					}
					else if(currentProdut.getProductID().equals("6"))
					{
						tvConfirmationText.setText("Tuma Startimes salio la Tsh  "+amount +" Kwenda meter namba "+etRefMobileNo.getText().toString()+".");
					}
					else if(currentProdut.getSystemServiceID().equals("16"))
					{
						tvConfirmationText.setText("Tuma "+amount +" Tsh kwenda Modem namba "+etRefMobileNo.getText().toString()+".");
					}
					else
					{
						tvConfirmationText.setText("Tuma "+amount +" Tshs kwenda namba "+etRefMobileNo.getText().toString()+".");
					}
					
					btnOkConfirmation.setOnClickListener(this);
					btnCancelConfirmation.setOnClickListener(this);
					show();

			 }
			 

			
		}
		else if(v==btnOkConfirmation)
		{
			dismiss();
			setContentView(R.layout.top_up_summary);
			tvSummary=(TextView)findViewById(R.id.tvSummaryText);
			btnOkSummary=(Button)findViewById(R.id.btn_Ok_Summary);
			btnContinue=(Button)findViewById(R.id.btn_Continue);
			btnOkSummary.setOnClickListener(this);
			btnContinue.setOnClickListener(this);
			 pd=ProgressDialog.show(context,    
					 null,"Please Wait..." , true);
			 pd.setContentView(R.layout.progress);
			 
			 
			 new Thread(new Runnable() 
		        {
		            public void run() 
		            {
		            	TopUpProcess topUpProcess=new TopUpProcess(context,pd,handler,currentProdut,etRefMobileNo.getText().toString(),etFromNo.getText().toString(),amount);
		            	TopUpStatus topUpStatus=topUpProcess.process();
			             
		            		if(topUpStatus!=null)
			            	{
		            			if(currentProdut.getProductID().equals("5"))
		            			{
		            				tvSummary.setText("Umetuma LUKU la Tsh "+topUpStatus.getTopUpAmount()+" kwenda Mtr No. "+etRefMobileNo.getText().toString()+".Asante kwa kutumia huduma ya BUTTON PAY.");	
		            			}
		            			else if(currentProdut.getProductID().equals("6"))
		            			{
		            				tvSummary.setText("Umetuma salio la Tsh "+topUpStatus.getTopUpAmount()+" kwenda kadi namba "+etRefMobileNo.getText().toString()+". Asante kwa kutumia huduma ya BUTTON PAY.");
		            			}
		            			else
		            			{
		            				tvSummary.setText("Umetuma Salio la Tshs "+topUpStatus.getTopUpAmount()+" kwenda namba "+etRefMobileNo.getText().toString()+".Asante kwa kutumia huduma ya BUTTON PAY.");
		            			}

		            			myhandler.post(new Runnable() 
				                {
				                    public void run() 
				                    {
				                        pd.dismiss(); 
				                   	    show();
				                    }
				                });
			            	}
			            }    
			 
			        }).start();  
		}
		else if(v==btnCancelConfirmation)
		{
			dismiss();
		}
		else if(v==btnOkSummary)
		{
			dismiss();
		}
		else if(v==btnContinue)
		{
			dismiss();
			new TopUpDialog(context, currentProdut).show();
		}
		else if(v==btnCancel)
		{
			dismiss();
		}
		 
	}
	

}
